
import { SearchTree } from '@szzj/ds';
import { findArrDiff, getTreeChildIds, getTreeParentIds } from '../../util';
import type { IRoleTree } from '@/types/systemManagement/role';

function Index({
  data,
  checkedKeys,
  setCheckedKeys,
  disabled,
  onChange,
  ...rest
}: {
  data: IRoleTree[];
  checkedKeys: string[];
  setCheckedKeys: (keys?: string[]) => void;
  disabled?: boolean;
  value?: string;
  onChange?: (value?: string[]) => void;
}) {
  //父节点长度为0时展开
  const expandKey = data && (data?.length > 1 ? [] : [data?.[0]?.id]);
  const loop = (
    data: IRoleTree[] | undefined,
    parentId = '0',
    deep = 0,
  ): IRoleTree[] | undefined => {
    return data?.map((item) => {
      if (item.children) {
        return {
          parentId,
          title: item?.name ?? item.title,
          key: item?.id ?? item.key,
          disabled: disabled,
          children: loop(item.children, item.id, deep + 1),
        };
      }
      return {
        parentId,
        title: item?.name ?? item.title,
        key: item?.id ?? item.key,
        disabled: disabled,
        // disabled: deep !== 0 && !checkedKeys?.includes(parentId),
      };
    });
  };
  //父子节点取消
  const filterTreeNode = (checkedKeysValue: string[]) => {
    const changeItem = findArrDiff(checkedKeys, checkedKeysValue);
    if (changeItem.type === 'add') {
      const newCheckedKeys = [
        ...new Set([
          ...getTreeParentIds(data, changeItem.diff[0]),
          ...(getTreeChildIds(data, changeItem.diff[0], []) || []),
          ...checkedKeysValue,
        ]),
      ];
      return newCheckedKeys;
    } else if (changeItem.type === 'delete') {
      const deleteChilds = getTreeChildIds(data, changeItem.diff[0], []);
      return checkedKeysValue.filter((item) => !deleteChilds?.includes(item));
    }
  };

  return (
    <SearchTree
      title=""
      checkedKeys={checkedKeys}
      treeData={loop(data)}
      defaultExpandedKeys={expandKey}
      onCheck={(checkedKeysValue: { checked: string[]; halfChecked: string[] }) => {
        if (disabled) {
          return;
        }
        const { checked } = checkedKeysValue;
        const newCheckedKeys = filterTreeNode(checked);
        setCheckedKeys(newCheckedKeys);
        onChange?.(newCheckedKeys);
      }}
      checkable
      showLine
      checkStrictly
      {...rest}
      onChange={onChange}
    />
  );
}
export default Index;
